package com.techsoul.common.core.util.codec;

/**
 * 系统工具类
 *
 * @author liuen
 */
public class PasswordUtils {

    // byte数组的大小
    public static final int NUM_BYTES = 8;

    // 散列算法
    public static final String HASH_ALGORITHM = "SHA-1";

    // 迭代次数
    public static final int HASH_INTERATIONS = 1024;

    /**
     * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
     *
     * @param plainPassword 明文密码
     */
    public static String entryptPassword(String plainPassword) {
        String plain = EncodeUtils.decodeHtml(plainPassword);
        byte[] salt = DigestUtils.genSalt(NUM_BYTES);
        byte[] hashPassword = DigestUtils.digest(plain.getBytes(), HASH_ALGORITHM, salt, HASH_INTERATIONS);
        return EncodeUtils.encodeHex(salt) + EncodeUtils.encodeHex(hashPassword);
    }

    /**
     * 验证密码
     *
     * @param plainPassword 明文密码
     * @param password      密文密码
     * @return 验证成功返回true
     */
    public static boolean validatePassword(String plainPassword, String password) {
        String plain = EncodeUtils.decodeHtml(plainPassword);
        byte[] salt = EncodeUtils.decodeHex(password.substring(0, 16));
        byte[] hashPassword = DigestUtils.digest(plain.getBytes(), HASH_ALGORITHM, salt, HASH_INTERATIONS);
        return password.equals(EncodeUtils.encodeHex(salt) + EncodeUtils.encodeHex(hashPassword));
    }

    public static void main(String[] args) {
        String password = "admin";
        String entryptPassword = entryptPassword(password);
        System.out.println("entryptPassword: " + entryptPassword);
        System.out.println("password: " + password);
        System.out.println("validatePassword: " + validatePassword(password, entryptPassword));
    }

}
